package com.ccq.farm.shiro.ec;/**
 * Created by HiWin10 on 2018-06-30.
 */

import com.ccq.farm.model.OauthUser;
import com.ccq.farm.service.OauthPermissionService;
import com.ccq.farm.service.OauthRoleService;
import com.ccq.farm.service.OauthUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author ccq
 * @create 2018-06-30 下午 12:15
 * ec 模块 shiro realm
 **/
public class EcShiroRealm extends AuthorizingRealm {

    @Autowired
    private OauthUserService oauthUserService;

    @Autowired
    private OauthRoleService oauthRoleService;

    @Autowired
    private OauthPermissionService oauthPermissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        OauthUser user = (OauthUser) principals.fromRealm(getName()).iterator().next();
        String userName = user.getUserName();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //根据用户名查找 角色,放入到 info 里
        Set<String> roles = oauthRoleService.findRoleByName(userName, "ec");

        info.setRoles(roles);

        Set<String> permissions = oauthPermissionService.findPerByName(userName, "ec");

        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        OauthUser userInfo = oauthUserService.findByUserNameAndPwd(token.getUsername(), String.valueOf(token.getPassword()), "ec");

        if (userInfo == null) {
            return null;
        }
        if (userInfo.getStatus() == 1) { //账户冻结
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo, //用户名
                userInfo.getUserPwd(), //密码
                getName()  //realm name
        );


        return authenticationInfo;
    }
}
